package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.service.DtsPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.service.impl
 * @Description:
 * @Date 2022/10/13 19:26
 */
@Service
public class DtsPermissionServiceImpl implements DtsPermissionService {

    @Autowired
    DtsPermissionMapper permissionMapper;

    @Override
    public Set<String> findById(Integer[] ids) {
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DtsPermission::getRoleId ,ids);
        wrapper.eq(DtsPermission::getDeleted,false);
        List<DtsPermission> permissionList = permissionMapper.selectList(wrapper);
        Set<String> perms = permissionList.stream().map(dtsPermission -> {
            return dtsPermission.getPermission();
        }).collect(Collectors.toSet());
        return perms;
    }

    @Override
    public Set<String> findPermissionByRoleid(Integer roleId) {
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsPermission::getRoleId,roleId);
        wrapper.eq(DtsPermission::getDeleted,false);
        List<DtsPermission> dtsPermissions = permissionMapper.selectList(wrapper);
        Set<String> collect = dtsPermissions.stream().map(dtsPermission -> {
            return dtsPermission.getPermission();
        }).collect(Collectors.toSet());
        return collect;
    }

    @Override
    public void updatePermissions(int roleId, List<String> permissions) {
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsPermission::getRoleId,roleId);
        permissionMapper.delete(wrapper);

        if (permissions != null && permissions.size() > 0){
            for (String permission : permissions) {
                DtsPermission perm = new DtsPermission();
                perm.setRoleId(roleId);
                perm.setAddTime(new Date());
                perm.setDeleted(false);
                perm.setUpdateTime(new Date());
                perm.setPermission(permission);
                permissionMapper.insert(perm);
            }
        }
    }


}
